package com.brtbeacon.app.webviewplugin;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.brtbeacon.sdk.webview.extension.BRTWebViewPlugin;

import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

/**
 * 智石WebView插件集成步骤演示DEMO:
 *
 * 1、如果Activity或Fragment的layout.xml资源文件中，WebView的父层容器的类型不是FrameLayout，请添加FrameLayout，并将WebView移动到里面，如下面代码：
 *
 * <FrameLayout>
 *     <WebView
 *             android:id="@+id/webView"
 *             android:layout_width="match_parent"
 *             android:layout_height="match_parent" />
 * </FrameLayout>
 *
 * 2、在Activity:onCreate()或者Fragment:onCreate()方法中，构造并初始化插件：brtWebViewPlugin = new BRTWebViewPlugin(this, webView, webViewParent);
 *
 * 3、在WebView页面加载完成后，调用插件方法：brtWebViewPlugin.setEnable(true);
 *
 * 4、在Activity:onDestroy()方法中，调用方法：brtWebViewPlugin.onDestroy();
 *
 * 5、插件需要申请运行时权限：
*     android.Manifest.permission.ACCESS_FINE_LOCATION
 *    android.Manifest.permission.ACCESS_COARSE_LOCATION
 *    android.Manifest.permission.CAMERA
 */

public class MapWebViewActivity extends AppCompatActivity {

    public final static String PARAM_URL = "param_url";

    private final static int PLUGIN_PERMISSION_CODE = 999;

    //public static final String URL = "http://p.brtbeacon.net/custom/shenzhen-lhjcy/navigator.html?signa=12f2d37568444a3795d33d25cc35ff9a&locatePOI=00230050F1030012&mapshow=true";
    //public static final String URL = "http://192.168.1.66:8080/demo/WebSDK/index.html";
    //public static final String URL = "http://p.brtbeacon.net/custom/wxc-nantong/mys_list.html";

    private WebView webView;
    private FrameLayout webViewParent;
    private BRTWebViewPlugin brtWebViewPlugin = null;
    private Handler handler = new Handler();
    private String url;
    private boolean needDownload = true;

    public static void startActivity(Context ctxt, String url) {
        Intent intent = new Intent(ctxt, MapWebViewActivity.class);
        intent.putExtra(PARAM_URL, url);
        ctxt.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        url = this.getIntent().getStringExtra(PARAM_URL);
        setContentView(R.layout.activity_map_webview);
        webView = findViewById(R.id.webView);
        //  WebView上级容器，必须为FrameLayout;
        webViewParent = findViewById(R.id.layoutFrame);
        //  根据链接是否包含brtbeacon判断是否开启智石插件。
        if (url.contains("brtbeacon")) {
            //  构造并初始化插件；
            brtWebViewPlugin = new BRTWebViewPlugin(this, webView, webViewParent);
            //  添加页面事件回调监听；
            brtWebViewPlugin.setPluginCallback(new BRTWebViewPlugin.BRTWebViewPluginCallback() {
                @Override
                public void onShare(String json) {
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        String title = jsonObject.getString("title");
                        String imgUrl = jsonObject.getString("imgUrl");
                        String desc = jsonObject.getString("desc");
                        String link = jsonObject.getString("link");
                        share(title, imgUrl, desc, link);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onDetails(String json) {
                    Toast.makeText(MapWebViewActivity.this, json, Toast.LENGTH_SHORT).show();
                }
            });
        }

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //  页面加载完成后5秒，开启插件。
                        if (brtWebViewPlugin != null) {
                            brtWebViewPlugin.setEnable(true);
                        }
                    }
                }, 5000);
            }

            //  处理打开第三方法APP
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!url.startsWith("http")) {
                    try {
                        // 以下固定写法
                        final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                        needDownload = false;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                sslErrorHandler.proceed();
            }
        });

        //  处理下载请求
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                if (needDownload) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    Uri uri = Uri.parse(url);
                    intent.addCategory(Intent.CATEGORY_BROWSABLE);
                    intent.setData(uri);
                    startActivity(intent);
                }
                needDownload = true;
            }
        });

        //  此处检查申请插件需要的运行时权限。
        List<String> permissionList = getRequestPermissions();
        if (!permissionList.isEmpty()) {
            requestPermissions(permissionList);
        } else {
            webView.loadUrl(url);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (brtWebViewPlugin != null) {
            brtWebViewPlugin.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (brtWebViewPlugin != null) {
            brtWebViewPlugin.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (brtWebViewPlugin != null) {
            brtWebViewPlugin.onDestroy();
        }
    }

    private void share(String title, String imgURL, String desc, String link) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/html");
        intent.putExtra(Intent.EXTRA_SUBJECT, title);
        intent.putExtra(Intent.EXTRA_TEXT, desc + " " + link);
        startActivity(Intent.createChooser(intent, "分享到"));
    }

    private List<String> getRequestPermissions() {
        List<String> permissions = new LinkedList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//判断当前系统的SDK版本是否大于23
            for (String permssion: permissionsNeedCheck) {
                if(ActivityCompat.checkSelfPermission(this, permssion) != PackageManager.PERMISSION_GRANTED) {
                    permissions.add(permssion);
                }
            }
        }
        return permissions;
    }

    private void requestPermissions(List<String> permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(permissions.toArray(new String[0]), PLUGIN_PERMISSION_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在requestPermissions时传入
            case PLUGIN_PERMISSION_CODE:
                boolean isAllGrant = true;
                for (int grantResult: grantResults) {
                    if (grantResult != PackageManager.PERMISSION_GRANTED) {
                        isAllGrant = false;
                        break;
                    }
                }
                if (!isAllGrant) {
                    Toast.makeText(getApplicationContext(), "权限申请失败，请手动前往设置开启", Toast.LENGTH_SHORT).show();
                    return;
                }

                webView.loadUrl(url);
                break;
            default:
                break;
        }
    }

    private static final List<String> permissionsNeedCheck;
    static {
        permissionsNeedCheck = new LinkedList<>();
        permissionsNeedCheck.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
        permissionsNeedCheck.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
        permissionsNeedCheck.add(android.Manifest.permission.CAMERA);
    }
}
